﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace Dll
{
    public class SqlHelp
    {
        private String dataBasePath;
        private String connectionString;
        public SqlHelp(String dataBasePath)
        {
            this.dataBasePath = dataBasePath;
            this.connectionString = String.Format("Data Source={0};Version=3;", dataBasePath);
        }
        public int ExecuteNonQuery(String sqlText, params System.Data.SQLite.SQLiteParameter[] parameters)
        {
            using (SQLiteConnection con = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(sqlText, con))
                {
                    cmd.Parameters.AddRange(parameters);
                    try
                    {
                        con.Open();
                        int result = cmd.ExecuteNonQuery(System.Data.CommandBehavior.CloseConnection);
                        return result;
                    }
                    catch (Exception)
                    {
                        con.Close();
                        throw;
                    }
                }
            }
        }

        public Object ExecuteScalar(String sqlText, params System.Data.SQLite.SQLiteParameter[] parameters)
        {
            using (SQLiteConnection con = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(sqlText, con))
                {
                    cmd.Parameters.AddRange(parameters);
                    try
                    {
                        con.Open();
                        Object result = cmd.ExecuteScalar(System.Data.CommandBehavior.CloseConnection);
                        return result;
                    }
                    catch (Exception)
                    {
                        con.Close();
                        throw;
                    }
                }
            }
        }

        public SQLiteDataReader ExecuteReader(String sqlText, params SQLiteParameter[] parameters)
        {
            SQLiteConnection con = new SQLiteConnection(connectionString);

            using (SQLiteCommand cmd = new SQLiteCommand(sqlText, con))
            {
                cmd.Parameters.AddRange(parameters);
                try
                {
                    con.Open();
                    SQLiteDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                    return dr;
                }
                catch (Exception)
                {
                    con.Close();
                    throw;
                }
            }

        }



    }
}
